<template>
    <div>
        <el-tree
            :data="categorys"
            :props="defaultProps"
            show-checkbox
            :default-expanded-keys="expandedKey"
            node-key="catId"
        >
            <span class="custom-tree-node" slot-scope="{ node, data }">
                <span>{{ node.label }}</span>
                <span>
                    <a v-if="node.level <= 2" @click="append(data)"> Append </a>
                    <a
                        v-if="node.childNodes.length == 0"
                        @click="open(node, data)"
                    >
                        Delete
                    </a>
                </span>
            </span>
        </el-tree>
    </div>
</template>

<script>
export default {
    data() {
        return {
            categorys: [],
            expandedKey: [],
            defaultProps: {
                children: "children",
                label: "name",
            },
        };
    },
    created() {
        this.getAllCategory();
    },
    methods: {
        //查询所有的分类信息
        getAllCategory() {
            this.$http({
                url: this.$http.adornUrl("/product/category/list"),
                method: "get",
            }).then(({ data }) => {
                this.categorys = data.data;
                console.log(this.categorys);
            });
        },
        //添加分类
        append(data) {
            console.log(data);
        },
        //删除分类信息
        remove(node, data) {
            var id = [data.catId];
            this.$http({
                url: this.$http.adornUrl("/product/category/delete"),
                method: "post",
                data: this.$http.adornData(id, false),
            }).then(({ data }) => {
                this.$message({
                    type: "success",
                    message: "删除成功!",
                });
                //刷新页面
                this.getAllCategory();
                this.expandedKey = [node.parent.data.catId];
            });
        },
        //点击删除按钮显示
        open(node, data) {
            this.$confirm(
                `此操作将永久删除【${data.name}】, 是否继续?`,
                "提示",
                {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                }
            ).then(() => {
                //调用删除方法
                this.remove(node, data);
            });
        },
    },
};
</script>
